<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="STM32CubeMX CAN TJA1050">
    <meta name="description" content="嵌入式 STM32 物联网领域的教程及精彩内容分享">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>STM32CubeMX | 36-使用CAN总线进行双板通信（TJA1050） | Mculover666</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Mculover666</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-list" style="zoom: 0.6;"></i>
      
      <span>系列教程</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/posts/578764034/">
          
          <span>STM32CubeMX</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>CSDN</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/download" class="waves-effect waves-light">
      
      <i class="fas fa-download" style="zoom: 0.6;"></i>
      
      <span>资源下载</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Mculover666</div>
        <div class="logo-desc">
            
            嵌入式 STM32 物联网领域的教程及精彩内容分享
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-list"></i>
			
			系列教程
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/posts/578764034/ " style="margin-left:75px">
				  
		          <span>STM32CubeMX</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			CSDN
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/download" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-download"></i>
			
			资源下载
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/23.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">STM32CubeMX | 36-使用CAN总线进行双板通信（TJA1050）</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/STM32CubeMX-TJA1050/">
                                <span class="chip bg-color">STM32CubeMX TJA1050</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/STM32CubeMX/" class="post-category">
                                STM32CubeMX
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-06-01
                </div>
                

                

                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>本篇详细的记录了如何使用STM32CubeMX配置 STM32F407ZGT6 的硬件CAN接口与另一个开发板之间通信。</p>
<span id="more"></span>

<h1 id="1-准备工作"><a href="#1-准备工作" class="headerlink" title="1. 准备工作"></a>1. 准备工作</h1><h2 id="硬件准备"><a href="#硬件准备" class="headerlink" title="硬件准备"></a>硬件准备</h2><ul>
<li>开发板</li>
</ul>
<p>首先需要准备一个开发板，这里我准备的是STM32F407ZGT6的开发板，称之为 1# 实验板。</p>
<ul>
<li>CAN收发器</li>
</ul>
<p>开发板板载一块CAN收发器TJA1050，如图中红框所示：</p>
<p><img src="https://img-blog.csdnimg.cn/20201125220324961.png"></p>
<h2 id="软件准备"><a href="#软件准备" class="headerlink" title="软件准备"></a>软件准备</h2><p>需要准备一份 TJA1050 的数据手册。</p>
<h2 id="实验说明"><a href="#实验说明" class="headerlink" title="实验说明"></a>实验说明</h2><p>本实验中还需要另外准备一块具备CAN收发功能的开发板，这里我使用STM32F767开发板，其板载CAN收发器也是TJA 1050，称之为 2# 实验板：<br><img src="https://img-blog.csdnimg.cn/20201126131013595.png"><br>两个开发板之间的连接方式如下：<br><img src="https://img-blog.csdnimg.cn/20201126131608917.png"><br>这样就形成了一个CAN总线的闭环通信网络，最高通信速度可达 1M bps/s：<br><img src="https://img-blog.csdnimg.cn/20201129085422105.png"></p>
<h1 id="2-使用STM32CubeMX生成工程"><a href="#2-使用STM32CubeMX生成工程" class="headerlink" title="2. 使用STM32CubeMX生成工程"></a>2. 使用STM32CubeMX生成工程</h1><h2 id="选择芯片型号"><a href="#选择芯片型号" class="headerlink" title="选择芯片型号"></a>选择芯片型号</h2><p>打开STM32CubeMX，打开MCU选择器：<br><img src="https://imgconvert.csdnimg.cn/aHR0cDovL21jdWxvdmVyNjY2LmNuL2ltYWdlLzIwMTkwODA2L2dCUDZnbG1VU0g4MC5wbmc?x-oss-process=image/format,png"></p>
<p>搜索并选中芯片<code>STM32F407ZGT6</code>：<br><img src="https://img-blog.csdnimg.cn/20200902100922112.png"></p>
<h2 id="配置时钟源"><a href="#配置时钟源" class="headerlink" title="配置时钟源"></a>配置时钟源</h2><ul>
<li>如果选择使用外部高速时钟（HSE），则需要在System Core中配置RCC；</li>
<li>如果使用默认内部时钟（HSI），这一步可以略过；</li>
</ul>
<p>这里我都使用外部时钟：<br><img src="https://img-blog.csdnimg.cn/20200902101014202.png"></p>
<h2 id="调试选项配置"><a href="#调试选项配置" class="headerlink" title="调试选项配置"></a><font color="red">调试选项配置</font></h2><p>默认没有配置下载引脚，烧录之后下载器将无法再检测到，这里我使用ST-Link，所以配置为SW选项：<br><img src="https://img-blog.csdnimg.cn/20200902101308732.png"></p>
<h2 id="配置串口"><a href="#配置串口" class="headerlink" title="配置串口"></a>配置串口</h2><p>开发板板载了一个CH340换串口，连接到USART1，但是引脚不是默认引脚，需要手动修改。</p>
<p>接下来开始配置<code>USART1</code>：<img src="https://img-blog.csdnimg.cn/20200902101420886.png"></p>
<h2 id="配置CAN外设"><a href="#配置CAN外设" class="headerlink" title="配置CAN外设"></a>配置CAN外设</h2><h3 id="CAN收发器"><a href="#CAN收发器" class="headerlink" title="CAN收发器"></a>CAN收发器</h3><p>开发板上CAN收发器（TJA1050）的原理图如下：<br><img src="https://img-blog.csdnimg.cn/20201125222610639.png#pic_center"><br>其中CAN_TX 和 CAN_RX 连接到CAN1外设：<br>|网络标号|引脚|<br>|:—:|:—:|<br>|CAN_TX|PA12|<br>|CAN_RX|PA11|</p>
<p>正点原子该款开发板上的PA12和PA11被复用，需要使用跳线帽来选择连接到CAN收发器。</p>
<h3 id="配置CAN1控制器"><a href="#配置CAN1控制器" class="headerlink" title="配置CAN1控制器"></a>配置CAN1控制器</h3><p>选中CAN1，点击使能“Master Mode”，在右边即可看到CAN1控制器的默认GPIO，与原理图上连接CAN收发器的引脚一致，无需修改：<br><img src="https://img-blog.csdnimg.cn/20201126131943496.png"></p>
<p><font color="red"><strong>配置CAN控制只需配置波特率，一般为500KHz，最高1MHz，其它保持默认即可。</strong></font></p>
<p>CAN总线的波特率比较特别，串口协议的波特率只支持一个确定值，而CAN总线的波特率<strong>支持一个较宽的范围</strong>，这也使得CAN总线的抗噪声性能大大增强。</p>
<p>CAN总线的波特率计算方式如下：</p>
<p>① <strong>确定CAN外设连接的外设总线时钟PCLK1</strong></p>
<p>此处CAN1连接到APB1外设总线上，在配置HCLK=168Mhz的基础上，PCLK=42Mhz。<br><img src="https://img-blog.csdnimg.cn/20201125224009777.png"><br>② <strong>确定分频系数</strong></p>
<p>此处将PCLK1进行7分频，为 42Mhz / 7 = 6Mhz，所以设置CAN1外设的分频系数为7：<br><img src="https://img-blog.csdnimg.cn/2020112522440384.png"><br>③ <strong>配置位段时序</strong></p>
<p>CAN协议的每一个数据位都分为许多时间段，如图：<br><img src="https://img-blog.csdnimg.cn/20201127115303333.png"></p>
<ul>
<li>同步段(SYNC_SEG)：位变化应该在此时间段内发生，只有一个时间片的固定长度(1 x tq)；</li>
<li>位段1(BS1)：定义采样点的位置，其持续长度可以在 1 到 16 个Tq之间调整；</li>
<li>位段2(BS2)：定义发送点的位置，其持续长度可以在 1 到 8 个Tq之间调整；</li>
<li>同步跳转宽度（SJW）：定义位段加长或缩短的上限，它可以在 1 到 4 个Tq之间调整；</li>
</ul>
<p>目标波特率是500khz，设：<br>$$<br>BS1+BS2+SJW = T<br>$$<br>根据：<br>$$<br>6Mhz/T = 6000khz / T =  500khz<br>$$<br>计算出：<br>$$<br>T = 12<br>$$<br>最后在BS1、BS2、SJW的每个范围内，调整出和为12即可，本文配置如下：<br><img src="https://img-blog.csdnimg.cn/20201125225028443.png"></p>
<h3 id="使能CAN1控制器接收中断"><a href="#使能CAN1控制器接收中断" class="headerlink" title="使能CAN1控制器接收中断"></a>使能CAN1控制器接收中断</h3><p><img src="https://img-blog.csdnimg.cn/20201126132429944.png"></p>
<h2 id="配置时钟树"><a href="#配置时钟树" class="headerlink" title="配置时钟树"></a>配置时钟树</h2><p>STM32F407ZGT6的最高主频到168M，使<code>HCLK = 168Mhz</code>即可：<br><img src="https://img-blog.csdnimg.cn/20200902112508876.png"></p>
<h2 id="生成工程设置"><a href="#生成工程设置" class="headerlink" title="生成工程设置"></a>生成工程设置</h2><p><img src="https://img-blog.csdnimg.cn/20201125225158214.png"></p>
<h2 id="代码生成设置"><a href="#代码生成设置" class="headerlink" title="代码生成设置"></a>代码生成设置</h2><p>最后设置生成独立的初始化文件：<br><img src="https://imgconvert.csdnimg.cn/aHR0cDovL21jdWxvdmVyNjY2LmNuL2ltYWdlLzIwMTkwODA2L1Q2V3ZTSzZEZnB0cy5wbmc?x-oss-process=image/format,png"></p>
<h2 id="生成代码"><a href="#生成代码" class="headerlink" title="生成代码"></a>生成代码</h2><p>点击<code>GENERATE CODE</code>即可生成MDK-V5工程：<br><img src="https://img-blog.csdnimg.cn/20200902104733463.png#pic_center"></p>
<h1 id="4-编写收发测试程序"><a href="#4-编写收发测试程序" class="headerlink" title="4. 编写收发测试程序"></a>4. 编写收发测试程序</h1><h2 id="4-1-重定向printf到串口1"><a href="#4-1-重定向printf到串口1" class="headerlink" title="4.1. 重定向printf到串口1"></a>4.1. 重定向printf到串口1</h2><pre><code class="c">/* USER CODE BEGIN 1 */
#if 1
#include &lt;stdio.h&gt;

int fputc(int ch, FILE *stream)
&#123;
    /* 堵塞判断串口是否发送完成 */
    while((USART1-&gt;SR &amp; 0X40) == 0);

    /* 串口发送完成，将该字符发送 */
    USART1-&gt;DR = (uint8_t) ch;

    return ch;
&#125;
#endif
/* USER CODE END 1 */
</code></pre>
<p>具体参考这篇博客：<a href="http://www.mculover666.cn/posts/2251182441/">STM32CubeMX_09 | 重定向printf函数到串口输出的多种方法</a></p>
<h2 id="4-2-编写CAN1收发测试代码"><a href="#4-2-编写CAN1收发测试代码" class="headerlink" title="4.2. 编写CAN1收发测试代码"></a>4.2. 编写CAN1收发测试代码</h2><h3 id="①编写CAN过滤器配置函数"><a href="#①编写CAN过滤器配置函数" class="headerlink" title="①编写CAN过滤器配置函数"></a>①编写CAN过滤器配置函数</h3><p>在 CAN 协议中，发送节点将报文广播给所有接收器。而接收节点会根据报文标识符的值来确定节点是否需要该消息，为了简化软件的工作， STM32 的 CAN 外设接收报文前会先使用过滤器检查，只接收需要的报文到 FIFO 中。</p>
<p>STM32的CAN控制器一共有 28 个过滤器，CAN1 和 CAN2 共用这些过滤器。</p>
<p>CAN过滤器结构体定义在<code>stm32f4xx_hal_can.h</code>文件中，在main.c中编写CAN过滤器配置函数（<strong>不进行任何过滤</strong>）：</p>
<pre><code class="c">/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* CAN过滤器配置函数 */
static void CANFilter_Config(void)
&#123;
    CAN_FilterTypeDef  sFilterConfig;
    
    sFilterConfig.FilterBank = 0;                       //CAN过滤器编号，范围0-27
    sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;   //CAN过滤器模式，掩码模式或列表模式
    sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;  //CAN过滤器尺度，16位或32位
    sFilterConfig.FilterIdHigh = 0x000 &lt;&lt; 5;            //32位下，存储要过滤ID的高16位
    sFilterConfig.FilterIdLow = 0x0000;                    //32位下，存储要过滤ID的低16位
    sFilterConfig.FilterMaskIdHigh = 0x0000;            //掩码模式下，存储的是掩码
    sFilterConfig.FilterMaskIdLow = 0x0000;
    sFilterConfig.FilterFIFOAssignment = 0;                //报文通过过滤器的匹配后，存储到哪个FIFO
    sFilterConfig.FilterActivation = ENABLE;            //激活过滤器
    sFilterConfig.SlaveStartFilterBank = 0;
    
    if (HAL_CAN_ConfigFilter(&amp;hcan1, &amp;sFilterConfig) != HAL_OK) &#123;
        printf(&quot;CAN Filter Config Fail!\r\n&quot;);
        Error_Handler();
    &#125;
    printf(&quot;CAN Filter Config Success!\r\n&quot;);

&#125;
/* USER CODE END 0 */
</code></pre>
<p>其中，不同配置模式下四个数据成员内容对应的含义：<br><img src="https://img-blog.csdnimg.cn/20201127120142947.png"></p>
<h3 id="②-定义接收和发送消息变量"><a href="#②-定义接收和发送消息变量" class="headerlink" title="② 定义接收和发送消息变量"></a>② 定义接收和发送消息变量</h3><p>在main.c文件中定义CAN接收和发送消息变量：</p>
<pre><code class="c">/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
static CAN_TxHeaderTypeDef        TxMessage;    //CAN发送的消息的消息头
static CAN_RxHeaderTypeDef        RxMessage;    //CAN接收的消息的消息头
/* USER CODE END PV */
</code></pre>
<h3 id="③-编写CAN接收中断处理函数"><a href="#③-编写CAN接收中断处理函数" class="headerlink" title="③ 编写CAN接收中断处理函数"></a>③ 编写CAN接收中断处理函数</h3><p>在main.c文件的最后编写CAN接收中断处理函数：</p>
<pre><code class="c">/* USER CODE BEGIN 4 */
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
&#123;
    uint8_t  data[8];
    HAL_StatusTypeDef    status;
    
    if (hcan == &amp;hcan1) &#123;    
        status = HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &amp;RxMessage, data);
        if (HAL_OK == status)&#123;                                          
            printf(&quot;---&gt;Data Receieve!\r\n&quot;);
            printf(&quot;RxMessage.StdId is %#x\r\n&quot;,  RxMessage.StdId);
            printf(&quot;data[0] is 0x%02x\r\n&quot;, data[0]);
            printf(&quot;data[1] is 0x%02x\r\n&quot;, data[1]);
            printf(&quot;data[2] is 0x%02x\r\n&quot;, data[2]);
            printf(&quot;data[3] is 0x%02x\r\n&quot;, data[3]);
            printf(&quot;&lt;---\r\n&quot;);
            
        &#125;
    &#125;
&#125;
/* USER CODE END 4 */
</code></pre>
<h3 id="④-编写CAN发送测试数据函数"><a href="#④-编写CAN发送测试数据函数" class="headerlink" title="④ 编写CAN发送测试数据函数"></a>④ 编写CAN发送测试数据函数</h3><pre><code class="c">/* CAN 发送数据测试函数 */
void CAN1_Send_Test()
&#123;
    uint8_t data[4] = &#123;0x01, 0x02, 0x03, 0x04&#125;;
    
    TxMessage.IDE = CAN_ID_STD;     //设置ID类型
    TxMessage.StdId = 0x222;        //设置ID号
    TxMessage.RTR = CAN_RTR_DATA;   //设置传送数据帧
    TxMessage.DLC = 4;              //设置数据长度
    
    if (HAL_CAN_AddTxMessage(&amp;hcan1, &amp;TxMessage, data, (uint32_t*)CAN_TX_MAILBOX0) != HAL_OK) &#123;
        printf(&quot;CAN send test data fail!\r\n&quot;);
        Error_Handler();
    &#125;
    printf(&quot;CAN send test data success!\r\n&quot;);
        
&#125;
</code></pre>
<h3 id="⑤-编写初始化函数"><a href="#⑤-编写初始化函数" class="headerlink" title="⑤ 编写初始化函数"></a>⑤ 编写初始化函数</h3><p>修改main函数，在其中配置CAN滤波器、启动CAN控制器、使能CAN控制器接收中断：</p>
<pre><code class="c"> /* USER CODE BEGIN 2 */
    printf(&quot;----- CAN Test Board #1 -----\r\n&quot;);
    
    /* 1. CAN Filter Config */
    CANFilter_Config();
    
    /* 2. CAN Start */
    if (HAL_CAN_Start(&amp;hcan1) != HAL_OK) &#123;
        printf(&quot;CAN Start Fail\r\n&quot;);
        Error_Handler();
    &#125;
    printf(&quot;CAN Start Success\r\n&quot;);
    
    /* 3. Enable CAN RX Interrupt */
    if (HAL_CAN_ActivateNotification(&amp;hcan1, CAN_IT_RX_FIFO0_MSG_PENDING) != HAL_OK) &#123;
        printf(&quot;CAN_IT_RX_FIFO0_MSG_PENDING Enable Fail\r\n&quot;);
        Error_Handler();
    &#125;
    printf(&quot;CAN_IT_RX_FIFO0_MSG_PENDING Enable Success\r\n&quot;);
    
  /* USER CODE END 2 */
</code></pre>
<h3 id="⑥-在main函数中循环发送测试数据"><a href="#⑥-在main函数中循环发送测试数据" class="headerlink" title="⑥ 在main函数中循环发送测试数据"></a>⑥ 在main函数中循环发送测试数据</h3><p>在while(1)中循环发送测试数据函数：</p>
<pre><code class="c">  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  &#123;
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
      /* 4. Send Data */
      CAN1_Send_Test();
      
      HAL_Delay(5000);

  &#125;
  /* USER CODE END 3 */
</code></pre>
<p>至此，1#测试板的配置和代码编写完成。</p>
<h1 id="5-编写2-测试板的代码"><a href="#5-编写2-测试板的代码" class="headerlink" title="5. 编写2#测试板的代码"></a>5. 编写2#测试板的代码</h1><p>第二块板的流程和第一块板的流程几乎相同，有几点需要改动。</p>
<p>① STM32F767的 PCLK1 = 54Mhz，所以要配置CAN控制器的分频系数为9，其余参数不变：</p>
<p><img src="https://img-blog.csdnimg.cn/20201126163734528.png"></p>
<p>② STM32F767开发板默认CAN控制器的接收引脚不匹配，需要修改到PA11：</p>
<p><img src="https://img-blog.csdnimg.cn/20201126163825879.png#pic_center"></p>
<p>③ 在代码中将打印信息修改为2#实验板：</p>
<p><img src="https://img-blog.csdnimg.cn/20201126163938373.png"></p>
<p>④ 在代码中修改发送数据包的ID号，为1#实验板的ID：</p>
<p><img src="https://img-blog.csdnimg.cn/20201126164030513.png"></p>
<p>其余地方一样。</p>
<h1 id="6-实验结果"><a href="#6-实验结果" class="headerlink" title="6. 实验结果"></a>6. 实验结果</h1><p>将两个程序分别编译、下载到开发板中，使用串口助手查看结果。</p>
<p>1#测试板（ID：0x111）的串口打印日志为：</p>
<p><img src="https://img-blog.csdnimg.cn/20201126164524498.png"></p>
<p>2#测试板（ID：0x222）的串口打印日志为：</p>
<p><img src="https://img-blog.csdnimg.cn/20201126164334589.png"></p>
<p><strong><font color="red">更多精彩文章及资源，请关注我的微信公众号：『mculover666』。</font></strong></p>
<p><img src="https://img-blog.csdnimg.cn/20200827112436112.png"></p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Mculover666</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.mculover666.cn/posts/3093870655/">http://www.mculover666.cn/posts/3093870655/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Mculover666</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/STM32CubeMX-TJA1050/">
                                    <span class="chip bg-color">STM32CubeMX TJA1050</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/we-chat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    
    <div class="livere-card card" data-aos="fade-up">
    <!-- 来必力City版安装代码 -->
    <div id="lv-container" class="card-content" data-id="city" data-uid="MTAyMC80Njg0OS8yMzM1MA">
        <script type="text/javascript">
            (function (d, s) {
                let j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') {
                    return;
                }

                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript。</noscript>
    </div>
    <!-- City版安装代码已完成 -->
</div>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/909631466/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/4.jpg" class="responsive-img" alt="STM32CubeMX | 37-使用RS485总线进行双板通信（SP3485）">
                        
                        <span class="card-title">STM32CubeMX | 37-使用RS485总线进行双板通信（SP3485）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本篇详细的记录了如何使用STM32CubeMX配置 STM32F407ZGT6 使用 RS485 总线与另一个开发板之间通信。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-06-02
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/STM32CubeMX/" class="post-category">
                                    STM32CubeMX
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/STM32CubeMX-SP3485/">
                        <span class="chip bg-color">STM32CubeMX SP3485</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/1132663314/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/23.jpg" class="responsive-img" alt="STM32CubeMX | 35-使用硬件FSMC驱动TFT-LCD屏幕（MCU屏，NT35510控制器）">
                        
                        <span class="card-title">STM32CubeMX | 35-使用硬件FSMC驱动TFT-LCD屏幕（MCU屏，NT35510控制器）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本篇详细的记录了如何使用STM32CubeMX配置 STM32f407ZGT6 的硬件FSMC外设驱动TFT-LCD屏幕。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-09-23
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/STM32CubeMX/" class="post-category">
                                    STM32CubeMX
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/STM32CubeMX-TFT-LCD/">
                        <span class="chip bg-color">STM32CubeMX TFT-LCD</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2016-2021</span>
            
            <span id="year">2016</span>
            <a href="/about" target="_blank">Mculover666</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">118.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2016";
                    var startMonth = "8";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="https://beian.miit.gov.cn" target="_blank">陇ICP备19002222号</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Mculover666" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:mculover666@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2412828003" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2412828003" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/wang-shi-wei-67-38/activities" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/wang-shi-wei-67-38/activities" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?6e1efa0988723a1db6356535db2ae6bd";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
